package com.szt.ynb.server.router.service;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.digest.Sha2Crypt;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

/***
 * 签名验证服务
 * 
 * @author wwy
 *
 */
@Service
public class SignService {
	
	@Value("${application.sign.salt}")
	private String salt;
	
	private static final Logger log = LoggerFactory.getLogger(SignService.class);
	
	public boolean checkSign(Map<String, String> params) {
		String sign = params.get("sign");
		params.remove("sign");
		if (StringUtils.isBlank(sign) || params == null) {
			return false;
		}
		String jsonStr = JSONObject.toJSONString(new TreeMap<>(params));
		String sign2 = null;
		try {
			sign2 = Sha2Crypt.sha256Crypt(jsonStr.getBytes("UTF-8"), salt);
		} catch (UnsupportedEncodingException e) {
			log.error("编码错误", e);
			return false;
		}
		if (sign2.equals(sign)) {
			return true;
		}
		return false;
	}
}
